package com.yang.service.impl;

import com.yang.constant.ConfiConstant;
import com.yang.dao.LoginDao;
import com.yang.dao.RegisterDao;
import com.yang.entity.RoomEntity;
import com.yang.entity.UserEntity;
import com.yang.entity.VerificationCodeEntity;
import com.yang.service.LoginService;
import com.yang.service.SendEmailService;
import com.yang.util.PublicUtil;
import com.yang.util.SecurityUtil;
import com.yang.util.SnowFlake;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    private static Logger logger = Logger.getLogger(LoginServiceImpl.class);

    @Resource
    LoginDao loginDao;

    @Resource
    RegisterDao registerDao;

    @Resource
    SendEmailService sendEmailService;

    @Override
    public Map<String, Object> Login(HttpServletRequest request,String emil, String password) {
        Map<String,Object> map = new HashMap<String, Object>();
        UserEntity userEntity = loginDao.selectUserByEmil(emil);
        if(userEntity == null){
            map.put("info","用户不存在");
            logger.error("用户不存在");
            return map;
        }
        try {
            password = SecurityUtil.encryptPassword(password);
            if(!password.equals(userEntity.getPassword())){
                map.put("info","密码不正确");
                logger.error("密码不正确");
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("info","网络错误");
            return map;
        }
        logger.info("userEntity = "+userEntity.toString());
        request.getSession().setAttribute("message","succeed Login");
        request.getSession().setAttribute("identfication",userEntity.getIdentification());
        request.getSession().setAttribute("id",userEntity.getId());
        request.getSession().setAttribute("userName",userEntity.getUserName());
        logger.info("ientfication"+request.getSession().getAttribute("identfication"));
        map.put("succeed","登陆成功");
        map.put("identification",userEntity.getIdentification());
        logger.info("succeed Login");
        return map;
    }

    @Override
    public Map<String, Object> getCodeByemil(String emil) {
        Map<String,Object> map = new HashMap<String, Object>();
        UserEntity userEntity = loginDao.selectUserByEmil(emil);
        if(userEntity == null){
            logger.error("用户不存在");
            map.put("info","QQ邮箱不存在！");
            return map;
        }
        if(!registerDao.deleteCode(emil)){
            logger.error("验证码表中存在记录不能删去");
            map.put("info","网络错误，请重新刷新");
            return map;
        }
        String code = PublicUtil.getSixNum();
        SnowFlake snowFlake = new SnowFlake(2,1);
        long id = snowFlake.getId();
        long time = System.currentTimeMillis();
        VerificationCodeEntity verificationCodeEntity = new VerificationCodeEntity(id,emil,code,time);
        //保存不了的不发
        if(!registerDao.saveCode(verificationCodeEntity)){
            logger.error("验证码保存失败");
            map.put("info","网络错误，请重新刷新");
            return map;
        }
        try {
            sendEmailService.sendEmil(code,emil);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("验证码发送失败");
            map.put("info","验证码发送失败");
            return map;
        }
        logger.info("验证码内容"+verificationCodeEntity.toString());
        map.put("info","验证码发送成功，有效时间为两分钟！");
        return map;
    }

    @Override
    public Map<String, Object> resetPasswordService(String emil, String password, String code) {
        Map<String,Object> map = new HashMap<String, Object>();

        VerificationCodeEntity verificationCodeEntity = registerDao.findVerificationCode(emil);
        if(verificationCodeEntity == null){
            map.put("info","请先发送验证码！");
            logger.error("数据库未找到验证码");
            return map;
        }
        if(!PublicUtil.judgeCodeTime(verificationCodeEntity.getTime())){
            map.put("info","验证码超时，请重新发送");
            logger.error("验证码超时！");
            return map;
        }
        if(!verificationCodeEntity.getCode().equals(code)){
            map.put("info","验证码不正确");
            logger.error("验证码不正确！");
            return map;
        }
        try {
            password = SecurityUtil.encryptPassword(password);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("加密失败");
            map.put("info","网络出错");
            return map;
        }
        UserEntity userEntity = loginDao.selectUserByEmil(emil);
        if(userEntity == null){
            logger.error("未找到用户！");
            map.put("info","网络出错！");
            return map;
        }
        userEntity.setPassword(password);
       if(! loginDao.updateUser(userEntity)){
           logger.error("用户保存失败！");
           map.put("info","网络出错！");
           return map;
       }
        logger.error("密码修改成功！");
        map.put("info","密码修改成功！");
       return map;
    }

    @Override
    public Map<String, Object> roomConditionService() {
        Map<String,Object> map = new HashMap<String, Object>();
        List<RoomEntity> list = loginDao.selectRoomEntity();
        if(list == null || list.size() == 0){
            map.put("info","error");
            return map;
        }
        List<RoomEntity> roomEntities = new ArrayList<RoomEntity>();
        for(RoomEntity roomEntity : list){
            if(roomEntity.getStatus().equals(ConfiConstant. UNEMPTY_ROOM)){
                roomEntities.add(roomEntity);
            }

        }
        map.put("info","succeed");
        map.put("roomList",roomEntities);
        return map;
    }
}